import { Injectable,HttpException } from '@nestjs/common';
import { UserEntity } from '../../entity/user.entity'
import {InjectRepository} from '@nestjs/typeorm'
import { registerDto } from './type'
import { Repository,Like, getConnection } from 'typeorm'
import { makeSalt, encryptPassword } from '../../utils/cryptogram';
import * as moment from 'moment';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>
  ) { }

  //注册
  async register(params: any): Promise<any> {
    const user = this.findOneByusername(params.username);
    if(!user) {
       throw new HttpException('用户已存在',400);
    }
    const salt = makeSalt();
    console.log(salt)
    const dateNow = moment().format("YYYY-MM-DD HH:mm:ss");
    const hashPwd = encryptPassword(params.password, salt); 
    const newParams = { ... params,password:hashPwd,createTime:dateNow,updateTime:dateNow,salt:salt};
    const sql = await this.userRepository.save(newParams)
    return sql.id;
  }

  //登录
  async login(body: any): Promise<string> {
      const res:any =  await this.userRepository.query('SELECT * FROM tt_user');
      return res;
  }

  //查询
  async findOne(paramas: any): Promise<any> {
    const { username,pageSize,page } = paramas;
    const size:number = pageSize ? pageSize : 10;

    let res:Array<any>;
    res =  await this.userRepository.find({
        take:pageSize || 10,
        skip: page ? (page-1)*size : 0,
        cache: true,
        order: {
            createTime: 'DESC'
        },
        where: {
          username: Like(`${paramas.username}%`)
        }
    });
    res  = res.map(e =>{
       return {
          ...e,
          createTime: moment(e.createTime).format("YYYY-MM-DD HH:MM:ss"),
          updateTime: moment(e.updateTime).format("YYYY-MM-DD HH:MM:ss"),
       }
    })
    return res;
  }

  
    //根据用户名完全相等查询
    async findOneByusername(username: any): Promise<any> {
      let res:Array<any>;
      if(username) {
        res =  await this.userRepository.find({
            username
        });
      }else{
        res = []
      }
      return res[0];
    }
}
